package com.mcyy.financemanager.controller;

import com.mcyy.financemanager.entity.User;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

//可重定向 可返回文件与视图等
@Controller
//跨域
@CrossOrigin
@RequestMapping("/financeManager")
public class FCcontroller {
    @Autowired
    private FRcontroller fRcontroller;
    //导出用户信息excel表格文件
    @GetMapping("/getuserExcel")
    @ResponseBody
    public void getuserExcel(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        List<User> users=fRcontroller.getalluser();
        //创建Excel文件
        HSSFWorkbook wb=new HSSFWorkbook();
        //创建Sheet页
        HSSFSheet sheet=wb.createSheet("用户信息表");
        //创建标题行
        HSSFRow titleRow=sheet.createRow(0);
        titleRow.createCell(0).setCellValue("用户名");
        titleRow.createCell(1).setCellValue("姓名");
        titleRow.createCell(2).setCellValue("手机号");
        titleRow.createCell(3).setCellValue("身份证号");
        //遍历数据 放到excel列中
        String state="";
        for(User user:users){
            HSSFRow dataRow=sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(user.getLoginName());
            dataRow.createCell(1).setCellValue(user.getUserName());
            dataRow.createCell(2).setCellValue(user.getPhoneNo());
            dataRow.createCell(3).setCellValue(user.getIdNo());
        }
        //设置下载时客户端Excel的名称
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=" + new String("用户信息".getBytes(),
                "iso-8859-1") + ".xls");
        OutputStream outputStream = response.getOutputStream();
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
    //到登录页面
    @ApiOperation(value = "到登录页面")
    @GetMapping("/login")
    public String tologinpage(){
        return "financeManager/login";
    }
    //进入首页
    @ApiOperation(value = "进入首页")
    @GetMapping("/index")
    public String index(){
        return "financeManager/index";
    }
}
